﻿using System;
using System.Collections;
using System.Threading;
using System.Net;
using System.Net.Security;
using System.Security;
using System.Security.Cryptography.X509Certificates;

namespace BTVPodcatcherNamespace
{
    public class BTVWriter
    {
        private DowloadInfo _downloadInfo;
        private MainForm _mainForm;
        public BTVWriter(DowloadInfo di, MainForm m)
        {
            _downloadInfo = di;
            _mainForm = m;
            ServicePointManager.ServerCertificateValidationCallback += delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            {
                return true;
            };
        }
         
        public void writeBTVProprties()
        {
            Thread.Sleep(_mainForm.writeMediaInfoAfter * 1000);

            try{
            string _btvserver = _mainForm.BTVServer;
            string _serverName = "http://" + _btvserver + ":" + _mainForm.BTVPort;
            if (_mainForm.useSSL)
            {
                _serverName = "https://"  + _btvserver + ":" + _mainForm.BTVPort;
            }
            string _password = _mainForm.BTVPassword;
            string _username = _mainForm.BTVUsername;
            BTVLicenseManager.BTVLicenseManager lm = new BTVLicenseManager.BTVLicenseManager();
            lm.Url = _serverName + "/wsdl/BTVLicenseManager.asmx";
            BTVLicenseManager.PVSPropertyBag pvspb = lm.Logon("", _username, _password);
            string autTicket = "";
            foreach (BTVLicenseManager.PVSProperty pvp in pvspb.Properties)
            {
                if (pvp.Name.Equals("AuthTicket"))
                {
                    autTicket = pvp.Value;
                }
            }
            bool t = false;
            bool d = false;
            bool e = false;
            bool ed = false;
            bool editable = false;
            bool r = false;
            bool oad = false;
            bool aStart = false;
            bool call = false;
            bool fix = false;
            bool dt = false;
            BTVLibrary.BTVLibrary library = new BTVLibrary.BTVLibrary();
            library.Url = _serverName + "/wsdl/BTVLibrary.asmx";
            BTVLibrary.PVSPropertyBag pvsPB = library.GetMediaByFullName(autTicket, _downloadInfo.Destination.FullName);

            ArrayList aProp = new ArrayList();//pvsPB.Properties);
                /*foreach (BTVLibrary.PVSProperty PP in aProp)
                {
                    if (PP.Name.Equals("Title"))
                    {
                        PP.Value = _downloadInfo.RSSItem.rssFeed.title;
                            //_ .Title;
                        t = true;
                    }
                    else if (PP.Name.Equals("Description"))
                    {
                        string dest = StringFilter.FilterMarkupTags(true, _downloadInfo.RSSItem.rssFeed.description.Replace("\r", "").Replace("\n", ""));
                        if (dest.Length > _mainForm.maxWriteAmount)
                        {
                            dest = dest.Substring(0, _mainForm.maxWriteAmount);
                        }
                        PP.Value = dest;
                        d = true;
                    }
                    else if (PP.Name.Equals("EpisodeTitle"))
                    {
                        PP.Value = _downloadInfo.RSSItem.title;
                        e = true;
                    }
                    else if (PP.Name.Equals("EpisodeDescription"))
                    {
                        string dest = StringFilter.FilterMarkupTags(true, _downloadInfo.RSSItem.description.Replace("\r", "").Replace("\n", ""));
                        if (dest.Length > _mainForm.maxWriteAmount)
                        {
                            dest = dest.Substring(0, _mainForm.maxWriteAmount);
                        }
                        PP.Value = dest;
                        ed = true;
                    }
                    else if (PP.Name.Equals("DisplayTitle"))
                    {
                        PP.Value = _downloadInfo.RSSItem.rssFeed.title;
                        dt = true;
                    }
                    else if (PP.Name.Equals("SortableName"))
                    {
                        PP.Value = "";
                    }
                    else if (PP.Name.Equals("Editable"))
                    {
                        PP.Value = "TRUE";
                        editable = true;
                    }else if (PP.Name.Equals("ReadOnly"))
                    {
                        if (_mainForm.setFilesToReadOnly)
                            PP.Value = "TRUE";
                        else
                            PP.Value = "False";
                        r = true;
                    }
                    else if (PP.Name.Equals("OriginalAirDate"))
                    {
                        PP.Value = _downloadInfo.RSSItem.pubDate.ToString("yyyyMMdd");
                        oad = true;
                    }
                    else if (PP.Name.Equals("ActualStart"))
                    {
                        PP.Value=""+DateTime.Now.ToFileTimeUtc();
                        aStart = true;
                    }
                    else if (PP.Name.Equals("StationCallsign"))
                    {
                        PP.Value = "Podcast";
                        call = true;
                    }
                    else if (PP.Name.Equals("Fixed"))
                    {
                        if (_mainForm.setFilesToReadOnly)
                            PP.Value = "TRUE";
                        else
                            PP.Value = "False";
                        fix = true;
                    }
                    
                }
                 */ 
                aProp.Clear();
                if (!call)
                {
                    BTVLibrary.PVSProperty pv1 = new BTVLibrary.PVSProperty();
                    pv1.Name = "StationCallsign";
                    pv1.Value = "Podcast";
                    aProp.Add(pv1);
                }
                if (!aStart)
                {
                    BTVLibrary.PVSProperty pv1 = new BTVLibrary.PVSProperty();
                    pv1.Name = "ActualStart";
                    pv1.Value =""+ DateTime.Now.ToFileTimeUtc();
                    aProp.Add(pv1);
                }
                if (!oad)
                {
                    BTVLibrary.PVSProperty pv1 = new BTVLibrary.PVSProperty();
                    pv1.Name = "OriginalAirDate";
                    pv1.Value = _downloadInfo.RSSItem.pubDate.ToString("yyyyMMdd");
                    aProp.Add(pv1);
                }
                if (!t)
                {
                    BTVLibrary.PVSProperty pv1 = new BTVLibrary.PVSProperty();
                    pv1.Name = "Title";
                    pv1.Value = _downloadInfo.RSSItem.rssFeed.title.Replace("’", "'");
                    aProp.Add(pv1);
                }
                if (!dt)
                {
                    BTVLibrary.PVSProperty pv1 = new BTVLibrary.PVSProperty();
                    pv1.Name = "DisplayTitle";
                    pv1.Value = _downloadInfo.RSSItem.rssFeed.title.Replace("’", "'");
                    aProp.Add(pv1);
                }
                if (!d)
                {
                    string dest = StringFilter.FilterMarkupTags(true, _downloadInfo.RSSItem.rssFeed.description.Replace("\r", "").Replace("\n", ""));
                    if (dest.Length > _mainForm.maxWriteAmount)
                    {
                        dest = dest.Substring(0, _mainForm.maxWriteAmount);
                    }
                    BTVLibrary.PVSProperty pv2 = new BTVLibrary.PVSProperty();
                    pv2.Name = "Description";
                    pv2.Value = dest.Replace("’", "'");
                    aProp.Add(pv2);
                }
                if (!e)
                {
                    BTVLibrary.PVSProperty pv3 = new BTVLibrary.PVSProperty();
                    pv3.Name = "EpisodeTitle";
                    pv3.Value = _downloadInfo.RSSItem.title.Replace("’", "'");
                    aProp.Add(pv3);
                }
                if (!ed)
                {
                    string dest = StringFilter.FilterMarkupTags(true, _downloadInfo.RSSItem.description.Replace("\r", "").Replace("\n", ""));
                    dest = dest.Replace("’", "'");
                    if (dest.Length > _mainForm.maxWriteAmount)
                    {
                        dest = dest.Substring(0, _mainForm.maxWriteAmount);
                    }
                    BTVLibrary.PVSProperty pv4 = new BTVLibrary.PVSProperty();
                    pv4.Name = "EpisodeDescription";
                    pv4.Value = dest;
                    aProp.Add(pv4);

                }
                if (!editable)
                {
                    BTVLibrary.PVSProperty pv5 = new BTVLibrary.PVSProperty();
                    pv5.Name = "Editable";
                    pv5.Value = "True";
                   // aProp.Add(pv5);
                }
                if (!r)
                {
                    BTVLibrary.PVSProperty pv6 = new BTVLibrary.PVSProperty();
                    pv6.Name = "ReadOnly";
                    if (_mainForm.setFilesToReadOnly)
                        pv6.Value = "True";
                    else
                        pv6.Value = "False";
                    aProp.Add(pv6);
                }
                if (!fix)
                {
                    BTVLibrary.PVSProperty pv7 = new BTVLibrary.PVSProperty();
                    pv7.Name = "Fixed";
                    if (_mainForm.setFilesToReadOnly)
                        pv7.Value = "True";
                    else
                        pv7.Value = "False";
                    aProp.Add(pv7);

                }
                if (true)
                {
                    BTVLibrary.PVSProperty pv7 = new BTVLibrary.PVSProperty();
                    pv7.Name = "Clip";
                    pv7.Value = "False";
                    aProp.Add(pv7);
                }if (true)
                {
                    BTVLibrary.PVSProperty pv7 = new BTVLibrary.PVSProperty();
                    pv7.Name = "GENRE";
                    pv7.Value = "Unknown";
                    aProp.Add(pv7);
                }
                if (true)
                {
                    BTVLibrary.PVSProperty pv7 = new BTVLibrary.PVSProperty();
                    pv7.Name = "TZBias";
                    pv7.Value = ( (TimeSpan)( DateTime.UtcNow - DateTime.Now ) ).TotalMinutes.ToString();
                    aProp.Add(pv7);
                }
                if (true)
                {
                    BTVLibrary.PVSProperty pv1 = new BTVLibrary.PVSProperty();
                    pv1.Name = "TargetStart";
                    pv1.Value = "" + DateTime.Now.ToFileTimeUtc();
                    aProp.Add(pv1);
                }
                if (true)
                {
                    BTVLibrary.PVSProperty pv1 = new BTVLibrary.PVSProperty();
                    pv1.Name = "Watched";
                    pv1.Value = "False";
                    aProp.Add(pv1);
                }

                BTVLibrary.PVSPropertyBag newBag = new BTVLibrary.PVSPropertyBag();
                newBag.Properties = (BTVLibrary.PVSProperty[])aProp.ToArray(typeof(BTVLibrary.PVSProperty));
                library.Url = _serverName + "/wsdl/BTVLibrary.asmx";

                library.EditMedia(autTicket, _downloadInfo.Destination.FullName, newBag);
                lm.Logoff(autTicket);
                System.Console.WriteLine("Properties Writen out");
                _downloadInfo.DownloadStatus = DownloadStatus.PropertiesWritten;
                _downloadInfo.ADownloadChangedOccured(new EventArgs());
              //  _downloadInfo.Message = "BTV Properties Writen Out";
            }
            catch (Exception e1)
            {
                _downloadInfo.DownloadStatus = DownloadStatus.FailedToWriteProperties;
                //_downloadInfo.Message = "Failed Writing BTV Properties";
                ConsoleForm.addMessage("Unable to write properties " + e1.Message);
                System.Console.WriteLine("Unable to write properties "+e1.Message);
                _downloadInfo.ADownloadChangedOccured(new EventArgs());
            }

        }
    }
}
